package com.demo.jianjunhuang.recyclerviewdemo;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;

/**
 * @author jianjunhuang.me@foxmail.com
 * @since 2017/6/2.
 */

public class MAdapter extends RecyclerView.Adapter<MAdapter.ViewHolder> {

  private List<User> users;

  private OnItemClickListener onItemClickListener;

  public MAdapter(List<User> users) {
    this.users = users;
  }

  public void setOnItemLongClickListener(OnItemClickListener itemClickListener) {
    this.onItemClickListener = itemClickListener;
  }

  interface OnItemClickListener {
    void click(View view, ViewHolder holder);
  }

  @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_user, parent, false);
    final ViewHolder holder = new ViewHolder(view);
    holder.view.setOnClickListener(new OnClickListener() {
      @Override public void onClick(View v) {
        onItemClickListener.click(v,holder);
      }
    });
    return holder;
  }

  @Override public void onBindViewHolder(ViewHolder holder, int position) {
    User user = users.get(position);
    holder.userAvatar.setImageResource(R.mipmap.ic_launcher_round);
    holder.userName.setText(user.getName());
  }

  @Override public int getItemCount() {
    return users.size();
  }

  static class ViewHolder extends RecyclerView.ViewHolder {
    ImageView userAvatar;
    TextView userName;
    View view;

    public ViewHolder(View itemView) {
      super(itemView);
      view = itemView;
      userAvatar = (ImageView) itemView.findViewById(R.id.img_avatar);
      userName = (TextView) itemView.findViewById(R.id.tv_username);
    }
  }
}
